/*
 ******************************************************************************
 * Parts of this code sample are licensed under Apache License, Version 2.0   *
 * Copyright (c) 2009, Android Open Handset Alliance. All rights reserved.    *
 *																			  *																			*
 * Except as noted, this code sample is offered under a modified BSD license. *
 * Copyright (C) 2010, Motorola Mobility, Inc. All rights reserved.           *
 * 																			  *
 * For more details, see MOTODEV_Studio_for_Android_LicenseNotices.pdf        * 
 * in your installation folder.                                               *
 ******************************************************************************
 */
package me.evis.mobile.sms2cal.provider;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class CalAlarmContentProvider extends ContentProvider {

    private Sms2CalDbHelper dbHelper;
    private static HashMap<String, String> CALALARM_PROJECTION_MAP;
    private static final String TABLE_NAME = "calalarm";
    private static final String AUTHORITY = "me.evis.mobile.sms2cal.provider.calalarmcontentprovider";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
            + "/" + TABLE_NAME);
    public static final Uri _ID_FIELD_CONTENT_URI = Uri.parse("content://"
            + AUTHORITY + "/" + TABLE_NAME.toLowerCase());
    public static final Uri CALEVENT_ID_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/calevent_id");
    public static final Uri TRIGGERWEEKS_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/triggerweeks");
    public static final Uri TRIGGERDAYS_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/triggerdays");
    public static final Uri TRIGGERHOURS_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/triggerhours");
    public static final Uri TRIGGERMINUTES_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/triggerminutes");
    public static final Uri TRIGGERSECONDS_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/triggerseconds");
    public static final Uri REPEAT_FIELD_CONTENT_URI = Uri.parse("content://"
            + AUTHORITY + "/" + TABLE_NAME.toLowerCase() + "/repeat");
    public static final Uri DESCRIPTION_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/description");
    public static final Uri TARGET_GCAL_ID_FIELD_CONTENT_URI = Uri
            .parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
                    + "/target_gcal_id");

    public static final String DEFAULT_SORT_ORDER = "_id ASC";

    private static final UriMatcher URL_MATCHER;

    private static final int CALALARM = 1;
    private static final int CALALARM__ID = 2;
    private static final int CALALARM_CALEVENT_ID = 3;
    private static final int CALALARM_TRIGGERWEEKS = 4;
    private static final int CALALARM_TRIGGERDAYS = 5;
    private static final int CALALARM_TRIGGERHOURS = 6;
    private static final int CALALARM_TRIGGERMINUTES = 7;
    private static final int CALALARM_TRIGGERSECONDS = 8;
    private static final int CALALARM_REPEAT = 9;
    private static final int CALALARM_DESCRIPTION = 10;
    private static final int CALALARM_TARGET_GCAL_ID = 11;

    // Content values keys (using column names)
    public static final String _ID = "_id";
    public static final String CALEVENT_ID = "calevent_id";
    public static final String TRIGGERWEEKS = "triggerWeeks";
    public static final String TRIGGERDAYS = "triggerDays";
    public static final String TRIGGERHOURS = "triggerHours";
    public static final String TRIGGERMINUTES = "triggerMinutes";
    public static final String TRIGGERSECONDS = "triggerSeconds";
    public static final String REPEAT = "repeat";
    public static final String DESCRIPTION = "description";
    public static final String TARGET_GCAL_ID = "target_gcal_id";

    public boolean onCreate() {
        dbHelper = new Sms2CalDbHelper(getContext(), true);
        return (dbHelper == null) ? false : true;
    }

    public Cursor query(Uri url, String[] projection, String selection,
            String[] selectionArgs, String sort) {
        SQLiteDatabase mDB = dbHelper.getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        switch (URL_MATCHER.match(url)) {
        case CALALARM:
            qb.setTables(TABLE_NAME);
            qb.setProjectionMap(CALALARM_PROJECTION_MAP);
            break;
        case CALALARM__ID:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("_id=" + url.getPathSegments().get(1));
            break;
        case CALALARM_CALEVENT_ID:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("calevent_id='" + url.getPathSegments().get(2) + "'");
            break;
        case CALALARM_TRIGGERWEEKS:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("triggerweeks='" + url.getPathSegments().get(2)
                    + "'");
            break;
        case CALALARM_TRIGGERDAYS:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("triggerdays='" + url.getPathSegments().get(2) + "'");
            break;
        case CALALARM_TRIGGERHOURS:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("triggerhours='" + url.getPathSegments().get(2)
                    + "'");
            break;
        case CALALARM_TRIGGERMINUTES:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("triggerminutes='" + url.getPathSegments().get(2)
                    + "'");
            break;
        case CALALARM_TRIGGERSECONDS:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("triggerseconds='" + url.getPathSegments().get(2)
                    + "'");
            break;
        case CALALARM_REPEAT:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("repeat='" + url.getPathSegments().get(2) + "'");
            break;
        case CALALARM_DESCRIPTION:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("description='" + url.getPathSegments().get(2) + "'");
            break;
        case CALALARM_TARGET_GCAL_ID:
            qb.setTables(TABLE_NAME);
            qb.appendWhere("target_gcal_id='" + url.getPathSegments().get(2)
                    + "'");
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
        String orderBy = "";
        if (TextUtils.isEmpty(sort)) {
            orderBy = DEFAULT_SORT_ORDER;
        } else {
            orderBy = sort;
        }
        Cursor c = qb.query(mDB, projection, selection, selectionArgs, null,
                null, orderBy);
        c.setNotificationUri(getContext().getContentResolver(), url);
        return c;
    }

    public String getType(Uri url) {
        switch (URL_MATCHER.match(url)) {
        case CALALARM:
            return "vnd.android.cursor.dir/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM__ID:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_CALEVENT_ID:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TRIGGERWEEKS:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TRIGGERDAYS:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TRIGGERHOURS:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TRIGGERMINUTES:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TRIGGERSECONDS:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_REPEAT:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_DESCRIPTION:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";
        case CALALARM_TARGET_GCAL_ID:
            return "vnd.android.cursor.item/vnd.me.evis.mobile.sms2cal.provider.calalarm";

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
    }

    public Uri insert(Uri url, ContentValues initialValues) {
        SQLiteDatabase mDB = dbHelper.getWritableDatabase();
        long rowID;
        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }
        if (URL_MATCHER.match(url) != CALALARM) {
            throw new IllegalArgumentException("Unknown URL " + url);
        }

        rowID = mDB.insert("calalarm", "calalarm", values);
        if (rowID > 0) {
            Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(uri, null);
            return uri;
        }
        throw new SQLException("Failed to insert row into " + url);
    }

    public int delete(Uri url, String where, String[] whereArgs) {
        SQLiteDatabase mDB = dbHelper.getWritableDatabase();
        int count;
        String segment = "";
        switch (URL_MATCHER.match(url)) {
        case CALALARM:
            count = mDB.delete(TABLE_NAME, where, whereArgs);
            break;
        case CALALARM__ID:
            segment = url.getPathSegments().get(1);
            count = mDB.delete(TABLE_NAME,
                    "_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_CALEVENT_ID:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "calevent_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERWEEKS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "triggerweeks="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERDAYS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "triggerdays="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERHOURS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "triggerhours="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERMINUTES:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "triggerminutes="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERSECONDS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "triggerseconds="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_REPEAT:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "repeat="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_DESCRIPTION:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "description="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TARGET_GCAL_ID:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.delete(TABLE_NAME,
                    "target_gcal_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
        getContext().getContentResolver().notifyChange(url, null);
        return count;
    }

    public int update(Uri url, ContentValues values, String where,
            String[] whereArgs) {
        SQLiteDatabase mDB = dbHelper.getWritableDatabase();
        int count;
        String segment = "";
        switch (URL_MATCHER.match(url)) {
        case CALALARM:
            count = mDB.update(TABLE_NAME, values, where, whereArgs);
            break;
        case CALALARM__ID:
            segment = url.getPathSegments().get(1);
            count = mDB.update(TABLE_NAME, values,
                    "_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_CALEVENT_ID:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "calevent_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERWEEKS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "triggerweeks="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERDAYS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "triggerdays="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERHOURS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "triggerhours="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERMINUTES:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "triggerminutes="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TRIGGERSECONDS:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "triggerseconds="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_REPEAT:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "repeat="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_DESCRIPTION:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "description="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;
        case CALALARM_TARGET_GCAL_ID:
            segment = "'" + url.getPathSegments().get(2) + "'";
            count = mDB.update(TABLE_NAME, values,
                    "target_gcal_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
        getContext().getContentResolver().notifyChange(url, null);
        return count;
    }

    static {
        URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase(), CALALARM);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/#",
                CALALARM__ID);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/calevent_id"
                + "/*", CALALARM_CALEVENT_ID);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
                + "/triggerweeks" + "/*", CALALARM_TRIGGERWEEKS);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/triggerdays"
                + "/*", CALALARM_TRIGGERDAYS);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
                + "/triggerhours" + "/*", CALALARM_TRIGGERHOURS);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
                + "/triggerminutes" + "/*", CALALARM_TRIGGERMINUTES);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
                + "/triggerseconds" + "/*", CALALARM_TRIGGERSECONDS);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/repeat"
                + "/*", CALALARM_REPEAT);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/description"
                + "/*", CALALARM_DESCRIPTION);
        URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
                + "/target_gcal_id" + "/*", CALALARM_TARGET_GCAL_ID);

        CALALARM_PROJECTION_MAP = new HashMap<String, String>();
        CALALARM_PROJECTION_MAP.put(_ID, "_id");
        CALALARM_PROJECTION_MAP.put(CALEVENT_ID, "calevent_id");
        CALALARM_PROJECTION_MAP.put(TRIGGERWEEKS, "triggerweeks");
        CALALARM_PROJECTION_MAP.put(TRIGGERDAYS, "triggerdays");
        CALALARM_PROJECTION_MAP.put(TRIGGERHOURS, "triggerhours");
        CALALARM_PROJECTION_MAP.put(TRIGGERMINUTES, "triggerminutes");
        CALALARM_PROJECTION_MAP.put(TRIGGERSECONDS, "triggerseconds");
        CALALARM_PROJECTION_MAP.put(REPEAT, "repeat");
        CALALARM_PROJECTION_MAP.put(DESCRIPTION, "description");
        CALALARM_PROJECTION_MAP.put(TARGET_GCAL_ID, "target_gcal_id");

    }
}
